package net.ermannofranco.xml.schema;

import java.util.List;

public class RestrictionSimpleContent extends SchemaTag implements
		BaseTypeContainer {

	private static final long serialVersionUID = 2909467582186538464L;
	private boolean typeAssigned;
	private BaseTypeContainer baseContainer;

	protected RestrictionSimpleContent(int level, SchemaTag container) {
		super("restriction", level, container);
	}

	/**
	 * @param simpleTypeNumber
	 * @return
	 */
	protected RestrictionSimpleContent setBase(XmlType type) {
		if (typeAssigned)
			throw new SchemaException("Type already assigned");
		addAttr("base", getLocalNS() + ":" + XmlType.getType(type));
		typeAssigned = true;
		baseContainer = type;
		return this;
	}

	/**
	 * @param typeRef
	 * @return
	 */
	protected RestrictionSimpleContent setBase(ContentType typeRef) {
		if (typeAssigned)
			throw new SchemaException("Type already assigned");
		addAttr("base", feedFormPrefix(typeRef.getTypeName()));
		typeAssigned = true;
		boolean simplicity = typeRef.isNotVeryComplex();
		if (!simplicity)
			throw new SchemaException(
					"Only types with simple content are allowed");
		baseContainer = typeRef;
		return this;
	}

	/**
	 * @param simpleTypeNumber
	 * @return
	 */
	// protected RestrictionSimpleContent setBase(SimpleType type) {
	// return setBase(type.getTypeName());
	// }

	/**
	 * @return
	 */
	public SimpleType setSimpleType() {
		if (typeAssigned)
			throw new SchemaException("Type already assigned");
		SimpleType t;
		add(t = new SimpleType(getLevel() + 1, this));
		typeAssigned = true;
		baseContainer = t;
		return t;
	}

	public RestrictionSimpleContent addEnumerationFacet(String... values) {
		if (values == null) {
			log.warn("values null!!!");
			return this;
		}
		for (int i = 0; i < values.length; i++) {
			IFacet facet = new Facet.Enumeration(getLevel() + 1, this,
					getBaseTypes().toArray(new XmlType[0]));
			facet.setValue(values[i]);
			add(facet);
		}
		return this;

	}

	/**
	 * @param facetType
	 * @param value
	 * @return
	 */
	public RestrictionSimpleContent addFacet(Facet facetType, String value) {
		IFacet facet;
		(facet = Facet.getFacet(facetType, getLevel(), this, getBaseTypes()
				.toArray(new XmlType[0]))).setValue(value);
		add(facet);
		return this;
	}

	/**
	 * @return
	 */
	public Attribute addTagAttribute() {
		Attribute att;
		add(att = new Attribute(getLevel() + 1, this));
		return att;
	}

	public List<XmlType> getBaseTypes() {
		return baseContainer.getBaseTypes();
	}

}
